from types import FunctionType

from django.db.models import Q
from django.shortcuts import render
from django.utils.safestring import mark_safe

from web import models
from web.utils.group import Option, get_choice_text, get_search_group_condition
from web.utils.pager import Pagernation


def get_level_text(text, field):
    """
    获取choice字段的文本
    :param text: choice字段的名称
    :param field: choice字段
    :return:
    """

    def inner(obj=None, is_header=None, *args, **kwargs):
        if is_header:
            return text
        method = 'get_%s_display' % field
        value = getattr(obj, field)
        if value == 2:
            state = 'btn btn-warning'
        elif value == 4 or value == 3:
            state = 'btn btn-info'
        else:
            state = 'btn btn-danger'
        field_text = getattr(obj, method)()
        tpl = "<a class='{} btn-xs'>{}</a>".format(state, field_text)

        return mark_safe(tpl)

    return inner


def attacklog_list(request, pk):
    list_display = [
        'attack_type',
        'src_ip',
        'src_ip_addr',
        'dst_ip',
        'dst_port',
        'protocol',
        get_level_text('风险级别', 'level'),
        get_choice_text('动作', 'net_action'),
        'record_time'
    ]
    model_class = models.SangforFwAttackLog
    # 配置组合搜索
    search_group = [
        Option('level'),
        Option('net_action')
    ]
    search_group_list = []
    for option_object in search_group:
        search_group_list.append(option_object.get_queryset_or_tuple(request, model_class))
    # 获取组合搜索条件
    conn = get_search_group_condition(search_group, request)

    # 获取搜索条件
    search_list = [
        'attack_type__contains',
        'src_ip__contains',
        'src_ip_addr__contains',
        'dst_ip__contains',
        'protocol__contains'
    ]
    keyword = request.GET.get("keyword", "").strip()
    con = Q()
    con.connector = "OR"
    if keyword:
        for item in search_list:
            con.children.append((item, keyword))

    obj = models.SangforFw.objects.filter(id=pk).first()
    data_time = obj.create_datetime
    queryset = models.SangforFwAttackLog.objects.filter(con).filter(**conn). \
        filter(create_datetime__year=data_time.year,
               create_datetime__month=data_time.month,
               create_datetime__day=data_time.day).order_by('-record_time')

    pager = Pagernation(request, queryset)
    # 1.处理表头
    header_list = []
    if list_display:
        for key_or_func in list_display:
            if isinstance(key_or_func, FunctionType):
                header_list.append(key_or_func(None, True))
            else:
                verbose_name = model_class._meta.get_field(key_or_func).verbose_name
                header_list.append(verbose_name)
    else:
        header_list.append(model_class._meta.model_name)
    # 2.处理表格内容
    data_list = queryset[pager.start:pager.end]
    body_list = []
    for row in data_list:
        tr_list = []
        if list_display:
            for key_or_func in list_display:
                if isinstance(key_or_func, FunctionType):
                    tr_list.append(key_or_func(row, False))
                else:
                    tr_list.append('' if getattr(row, key_or_func) == None else getattr(row, key_or_func))
        else:
            tr_list.append(row)
        body_list.append(tr_list)

    pager = Pagernation(request, queryset)
    context = {
        'body_list': body_list,
        'header_list': header_list,
        'pager': pager,
        'keyword': keyword,
        'search_group_row_list': search_group_list
    }
    return render(request, 'list.html', context)
